<template>
  <div class="ruoyi-dashboard">
    <!-- 第一行两个主模块 -->
    <el-row :gutter="20">
      <!-- 模块1：产品列表与畅销/缺货药品 -->
      <el-col :span="12">
        <el-card class="module-card">
          <template #header>
            <div class="card-header">
              <span>产品管理</span>
            </div>
          </template>
          <div class="framework-container">
            <div class="product-group">
              <h3 class="group-title">产品列表</h3>
              <div class="scroll-wrapper"
                   @mouseenter="stopScroll"
                   @mouseleave="startScroll">
                <div class="scroll-container" ref="scrollContainer">
                  <ul class="product-list">
                    <li v-for="(item, index) in loopedProductList" :key="index">{{ item }}</li>
                  </ul>
                </div>
              </div>
            </div>
            <div class="product-group">
              <h3 class="group-title">畅销前三</h3>
              <ul class="product-list">
                <li v-for="(item, index) in topSelling" :key="index">{{ item }}</li>
              </ul>
            </div>
            <div class="product-group">
              <h3 class="group-title">缺货药品</h3>
              <ul class="product-list1">
                <li v-for="(item, index) in shortageDrugs" :key="index">{{ item }}</li>
              </ul>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 销售量与销售额模块 -->
      <el-col :span="12">
        <el-card class="module-card">
          <template #header>
            <div class="card-header"><span>销售量与销售额</span></div>
          </template>
          <div class="sales-container">
            <div class="card-grid">
              <div class="stat-card" v-for="(item, index) in salesData" :key="index">
                <span class="card-label">{{ item.label }}</span>
                <span class="card-value">{{ item.value }}</span>
                <div class="card-icon">{{ item.icon }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第二行模块 -->
    <el-row :gutter="20" class="mt-20">
      <!-- 药房药品分布饼图 -->
      <el-col :span="12">
        <el-card class="module-card">
          <template #header>
            <div class="card-header">
              <span>药房库存分布情况</span>
              <span class="total-count">总库存：{{ totalStock }}</span>
            </div>
          </template>
          <div class="chart-container">
            <div ref="drugDistributionChart" class="distribution-chart" />
            <div class="chart-legend">
              <div class="legend-item" v-for="(item, index) in stockAggregation" :key="index">
                <span class="color-dot" :style="{ backgroundColor: chartColors[index] }"></span>
                <span class="legend-name">{{ item.name }}</span>
                <span class="legend-value">{{ item.value }}件（{{ ((item.value / totalStock) * 100).toFixed(1) }}%）</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 进货开销与药房售出量 -->
      <el-col :span="12">
        <el-card class="module-card">
          <template #header>
            <div class="card-header"><span>进货开销与药房售出量</span></div>
          </template>
          <div class="purchase-container">
            <div class="card-grid">
              <div class="stat-card" v-for="(item, index) in purchaseData" :key="index">
                <span class="card-label">{{ item.label }}</span>
                <span class="card-value">{{ item.value }}</span>
                <div class="card-icon">{{ item.icon }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>


<script>
import * as echarts from 'echarts'
import drugAndPharmacy from "@/api/pharmacy/mixins/drugAndPharmacy.js"
import { listPatient_drug } from "@/api/patient_drug/patient_drug"
import { listDrug_warehouse_stock } from "@/api/warehouse/drug_warehouse_stock"
import { listManagement } from "@/api/BasicSettings/management"
import { listPharmacyStock } from "@/api/pharmacy/pharmacyStock";
import { listPharmacy } from "@/api/pharmacy/pharmacy";

export default {
  mixins: [drugAndPharmacy],
  data() {
    return {
      scrollSpeed: 40,  // 滚动速度（毫秒）
      scrollPosition: 0, // 当前滚动位置
      isHovering: false, // 鼠标悬停状态
      scrollTimer: null,
      scrollStep: 1,   // 每次滚动步长（像素）
      isScrolling: false,

      pharmacySales: [],
      productList: [],
      topSelling: [],
      shortageDrugs: [],
      salesData: [],
      pharmacyData: [],
      chartColors: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C'],
      purchaseData: [],
      drugSales: [],
      loadStatus: {
        drugSales: 'loading',
        drugList: 'loading',
        pharmacyList: 'loading',
        stockData: 'loading',
        drugType: 'loading'
      },
      allWarehouses: [],
      warehouseNames: {},
      drugTypeMap: {},
      drugAmountMap: {},
      categorySalesData: {
        chinese: {sales: 0, amount: 0},
        western: {sales: 0, amount: 0}
      },
      pharmacyStockData: [],
      pharmacyNameMap: {},
      stockAggregation: [],
    }
  },
  // 新增计算属性
  computed: {
    loopedProductList() {
      // 将列表复制一份实现无缝滚动
      return [...this.productList, ...this.productList];
    },
    totalStock() {
      return this.stockAggregation.reduce((sum, item) => sum + item.value, 0);
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.startScroll();
    });
  },

  beforeUnmount() {
    this.stopScroll();
  },

  watch: {
    productList: {
      handler() {
        this.$nextTick(() => {
          if (this.productList.length > 6) {
            this.startScroll();
          } else {
            this.stopScroll();
          }
        });
      },
      deep: true
    }
  },

  methods: {
    startScroll() {
      if (this.scrollTimer) clearInterval(this.scrollTimer);
      if (this.productList.length <= 6) return; // 列表项少时不滚动

      const container = this.$refs.scrollContainer;
      if (!container) return;

      this.scrollTimer = setInterval(() => {
        if (this.isHovering) return; // 鼠标悬停时暂停

        this.scrollPosition += 1;

        // 到达底部时重置位置
        if (this.scrollPosition >= container.scrollHeight / 2) {
          this.scrollPosition = 0;
        }

        container.style.transform = `translateY(-${this.scrollPosition}px)`;
      }, this.scrollSpeed);
    },

    stopScroll() {
      if (this.scrollTimer) {
        clearInterval(this.scrollTimer);
        this.scrollTimer = null;
      }
    },

    // 新增鼠标事件处理
    handleMouseEnter() {
      this.isHovering = true;
    },

    handleMouseLeave() {
      this.isHovering = false;
    },

    extractDrugNames() {
      return this.drugList.map(drug => {
        const name = drug.drugName || drug.name || '未知药品'
        return {id: drug.drugId || drug.id, name}
      }).filter(item => item.name !== '未知药品')
    },

    async getDrugTypeData() {
      this.loadStatus.drugType = 'loading'
      try {
        const response = await listManagement({pageNum: 1, pageSize: 10000})
        if (response && Array.isArray(response.rows)) {
          response.rows.forEach(drug => {
            const drugId = drug.drugId;
            const drugType = drug.typeName;
            const drugPrice = Number(drug.price) || 0;
            if (drugId && drugType) {
              this.drugTypeMap[drugId] = drugType;
            }
            if (drugId && drugPrice) {
              this.drugAmountMap[drugId] = drugPrice;
            }
          })
          this.loadStatus.drugType = 'success'
        } else {
          throw new Error('药品类型接口返回格式错误')
        }
      } catch (error) {
        this.loadStatus.drugType = 'error'
        this.$message.error(`药品类型数据加载失败: ${error.message}`)
      }
    },

    async getDrugSalesData() {
      this.loadStatus.drugSales = 'loading';
      try {
        if (this.loadStatus.drugType !== 'success') {
          await new Promise(resolve => {
            const checkStatus = setInterval(() => {
              if (this.loadStatus.drugType !== 'loading') {
                clearInterval(checkStatus);
                resolve();
              }
            }, 100);
          });
        }

        // 确保药房名称映射已加载
        if (Object.keys(this.pharmacyNameMap).length === 0) {
          await this.getPharmacyNameMap();
        }

        // 获取真实的药房销售数据（这里需要根据你的实际API调整）
        const params = { pageNum: 1, pageSize: 10000 };
        const response = await listPatient_drug(params);
        if (!response || !Array.isArray(response.rows)) {
          throw new Error('取药接口返回格式错误');
        }
        const drugRecords = response.rows;

        // 按药房统计销售数据
        const pharmacySalesMap = {};
        drugRecords.forEach(record => {
          const pharmacyId = record.pharmacyId; // 根据实际字段名调整
          const quantity = Number(record.quantity) || 0;

          if (pharmacyId && quantity > 0) {
            pharmacySalesMap[pharmacyId] = (pharmacySalesMap[pharmacyId] || 0) + quantity;
          }
        });

        // 转换为数组并使用真实的药房名称
        this.pharmacySales = Object.entries(pharmacySalesMap).map(([pharmacyId, quantity]) => ({
          pharmacyId,
          quantity,
          name: this.pharmacyNameMap[pharmacyId] || `药房${pharmacyId}` // 使用映射的名称
        }));

        // 保留其他销售数据逻辑
        let chineseSales = 0, chineseAmount = 0;
        let westernSales = 0, westernAmount = 0;
        drugRecords.forEach(record => {
          const drugId = record.drugId;
          const quantity = Number(record.quantity) || 0;
          const totalAmount = Number(record.totalAmount) || 0;
          if (!drugId || quantity <= 0) return;

          const drugType = this.drugTypeMap[drugId] || '';
          if (drugType.includes('中药')) {
            chineseSales += quantity;
            chineseAmount += totalAmount;
          } else if (drugType.includes('西药')) {
            westernSales += quantity;
            westernAmount += totalAmount;
          }
        });
        this.categorySalesData = {
          chinese: { sales: chineseSales, amount: chineseAmount },
          western: { sales: westernSales, amount: westernAmount }
        };

        const salesMap = {};
        drugRecords.forEach(record => {
          const drugName = record.drugName || '未知药品';
          const quantity = Number(record.quantity) || 0;
          if (drugName !== '未知药品') {
            salesMap[drugName] = (salesMap[drugName] || 0) + quantity;
          }
        });
        this.drugSales = Object.entries(salesMap)
          .map(([drug_name, totalQuantity]) => ({ drug_name, totalQuantity }))
          .sort((a, b) => b.totalQuantity - a.totalQuantity);

        this.loadStatus.drugSales = 'success';
        this.initDrugData();
        this.initPurchaseData();
        this.initSalesData();
      } catch (error) {
        this.loadStatus.drugSales = 'error';
        this.$message.error(`销量数据加载失败: ${error.message}`);
        this.initDrugData();
        this.initPurchaseData();
      }
    },

    async getPharmacyNameMap() {
      this.loadStatus.pharmacyMap = 'loading';
      try {
        const response = await listPharmacy({ pageNum: 1, pageSize: 10000 });

        if (response && Array.isArray(response.rows)) {
          this.pharmacyNameMap = response.rows.reduce((map, pharmacy) => {
            // 根据实际API返回的字段名调整
            const id = pharmacy.pharmacyId || pharmacy.id;
            const name = pharmacy.pharmacyName || pharmacy.name;

            if (id && name) {
              map[id] = name;
            }
            return map;
          }, {});

          this.loadStatus.pharmacyMap = 'success';
        } else {
          throw new Error('药房接口返回格式错误');
        }
      } catch (error) {
        console.error('获取药房名称映射失败:', error);
        this.loadStatus.pharmacyMap = 'error';
        this.$message.error('获取药房数据失败');
        this.pharmacyNameMap = {};
      }
    },

    async getPharmacyStockData() {
      // 可以保留原有逻辑或也改为硬编码数据
      try {
        await this.getPharmacyNameMap();
        const response = await listPharmacyStock({pageNum: 1, pageSize: 10000});
        if (response && Array.isArray(response.rows)) {
          this.pharmacyStockData = response.rows;
          const stockMap = {};
          this.pharmacyStockData.forEach(stock => {
            const pharmacyId = stock.pharmacyId;
            const quantity = Number(stock.quantity) || 0;
            if (pharmacyId) {
              stockMap[pharmacyId] = (stockMap[pharmacyId] || 0) + quantity;
            }
          });

          this.stockAggregation = Object.entries(stockMap).map(([pharmacyId, totalQuantity]) => ({
            name: this.pharmacyNameMap[pharmacyId] || `未知药房${pharmacyId}`,
            value: totalQuantity
          })).filter(item => item.value > 0);
          this.initDrugDistributionChart();
        }
      } catch (error) {
        this.$message.error("获取药房库存数据失败");
      }
    },

    async getStockData() {
      this.loadStatus.stockData = 'loading'
      try {
        const response = await listDrug_warehouse_stock({pageNum: 1, pageSize: 10000})
        if (!response || !Array.isArray(response.rows)) {
          throw new Error('库存接口返回格式错误')
        }
        const stockRecords = response.rows || []

        this.allWarehouses = [...new Set(stockRecords.map(item => item.warehouseId))]
        this.warehouseNames = stockRecords.reduce((map, item) => {
          if (item.warehouseId && item.warehouseName) {
            map[item.warehouseId] = item.warehouseName
          }
          return map
        }, {})

        const drugStockMap = {}
        stockRecords.forEach(record => {
          const drugId = record.drugId;
          const warehouseId = record.warehouseId;
          const quantity = Number(record.quantity) || 0;
          if (!drugStockMap[drugId]) {
            drugStockMap[drugId] = {
              drugId,
              warehouses: new Set(),
              warehousesWithStock: new Set()
            }
          }
          drugStockMap[drugId].warehouses.add(warehouseId)
          if (quantity > 0) {
            drugStockMap[drugId].warehousesWithStock.add(warehouseId)
          }
        })

        const allDrugs = this.extractDrugNames()
        const shortageDrugIds = []
        const partialShortageDrugIds = []
        Object.keys(drugStockMap).forEach(drugId => {
          const stockInfo = drugStockMap[drugId]
          if (stockInfo.warehousesWithStock.size === 0) {
            shortageDrugIds.push(drugId)
          } else if (stockInfo.warehouses.size > stockInfo.warehousesWithStock.size) {
            partialShortageDrugIds.push(drugId)
          }
        })

        const allDrugMap = allDrugs.reduce((map, drug) => {
          map[drug.id] = drug.name
          return map
        }, {})
        const fullShortageNames = shortageDrugIds.map(id => allDrugMap[id] || `未知药品(${id})`)
        const partialShortageNames = partialShortageDrugIds.map(id => {
          const lackWarehouses = [...drugStockMap[id].warehouses].filter(wId => !drugStockMap[id].warehousesWithStock.has(wId))
          const lackNames = lackWarehouses.map(wId => this.warehouseNames[wId] || `库房${wId}`)
          return `${allDrugMap[id] || `未知药品(${id})`}（${lackNames.join(',')}缺货）`
        })

        this.shortageDrugs = [...new Set([...fullShortageNames, ...partialShortageNames])]
        this.loadStatus.stockData = 'success'
      } catch (error) {
        this.loadStatus.stockData = 'error'
        this.$message.error(`库存数据加载失败: ${error.message}`)
        this.shortageDrugs = ['无法获取库存数据']
      }
    },

    initDrugData() {
      const allDrugs = this.extractDrugNames().map(item => item.name)
      this.productList = allDrugs || []

      this.$nextTick(() => {
        if (this.productList.length > 6) {
          this.startScroll()
        } else {
          this.stopScroll()
        }
      })

      if (this.loadStatus.drugSales === 'success') {
        this.topSelling = this.drugSales.length > 0
          ? this.drugSales.slice(0, 3).map(item => item.drug_name)
          : ['暂无销量数据']
      } else if (this.loadStatus.drugSales === 'loading') {
        this.topSelling = ['加载中...']
      } else {
        this.topSelling = allDrugs.slice(0, 3)
      }
    },

    initPharmacyData() {
      this.pharmacyData = this.pharmacyList.map(pharmacy => ({
        name: pharmacy.name || pharmacy.pharmacyName || '未知药房',
        count: Number(pharmacy.drugCount || pharmacy.count || 0)
      })).filter(item => item.count > 0)
    },

    initSalesData() {
      const chineseSales = this.categorySalesData.chinese?.sales || 0;
      const chineseAmount = this.categorySalesData.chinese?.amount || 0;
      const westernSales = this.categorySalesData.western?.sales || 0;
      const westernAmount = this.categorySalesData.western?.amount || 0;

      const formatAmount = (num) => `¥${num.toFixed(2)}`;

      this.salesData = [
        { label: '中药销售量', value: chineseSales, icon: '📊' },
        { label: '中药销售额', value: formatAmount(chineseAmount), icon: '💰' },
        { label: '西药销售量', value: westernSales, icon: '📊' },
        { label: '西药销售额', value: formatAmount(westernAmount), icon: '💰' },
        { label: '昨日销售额', value: '¥3500', icon: '📅' },
        { label: '今日销售额', value: '¥4200', icon: '📈' },
        { label: '总销量（今日）', value: (chineseSales + westernSales), icon: '📊' }
      ];

      // 使用真实的药房销售数据
      const pharmacySalesData = this.pharmacySales.map(pharmacy => ({
        label: `${pharmacy.name}取药数量`,
        value: pharmacy.quantity,
        icon: '🏥'
      }));

      this.purchaseData = [...[
        { label: '药品进货开销', value: '¥15000', icon: '📦' },
        { label: '物资进货开销', value: '¥8000', icon: '🧺' }
      ], ...pharmacySalesData].slice(0, 4);
    },

    initPurchaseData() {
      const purchaseCosts = [
        { label: '药品进货开销', value: '¥15000', icon: '📦' },
        { label: '物资进货开销', value: '¥8000', icon: '🧺' }
      ];

      // 使用真实的药房销售数据
      const pharmacySalesData = this.pharmacySales.map(pharmacy => ({
        label: `${pharmacy.name}取药数量`,
        value: pharmacy.quantity,
        icon: '🏥'
      }));

      this.purchaseData = [...purchaseCosts, ...pharmacySalesData].slice(0, 4);
    },

    initDrugDistributionChart() {
      const chartDom = this.$refs.drugDistributionChart;
      if (!chartDom) return;

      if (!this.stockAggregation || this.stockAggregation.length === 0) {
        if (this.chartInstance) this.chartInstance.clear();
        return;
      }

      if (!this.chartInstance) {
        this.chartInstance = echarts.init(chartDom);
      }

      const totalStock = this.stockAggregation.reduce((sum, item) => sum + item.value, 0);
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}<br/>库存总量：{c}件<br/>占比：{d}%'
        },
        series: [{
          type: 'pie',
          radius: ['45%', '70%'],
          center: ['50%', '45%'],
          data: this.stockAggregation.map(item => ({
            name: item.name,
            value: item.value
          })),
          itemStyle: {borderRadius: 8, borderColor: '#fff', borderWidth: 2},
          label: {show: false},
          labelLine: {show: false},
          emphasis: {scale: true, scaleOffset: 5}
        }],
        color: this.chartColors
      };

      this.chartInstance.setOption(option);
    }

  },
  created() {
    this.getPharmacyNameMap()
      .then(() => this.getDrugTypeData())
      .then(() => {
        setTimeout(() => {
          this.getDrugSalesData();
          this.getStockData();
          this.getPharmacyStockData();
        }, 100);
      })
      .catch(error => {
        console.error('初始化失败:', error);
        this.getDrugSalesData();
        this.getStockData();
        this.getPharmacyStockData();
      });
  }
}
</script>

<style scoped lang="scss">
.scroll-wrapper {
  height: 200px;
  overflow: hidden;
  position: relative;
}

.ruoyi-dashboard {
  padding: 20px;
  background-color: #fff;
  color: #333;
  height: 100vh;
  box-sizing: border-box;
  overflow: hidden;

  .el-row {
    height: calc(50% - 10px);
  }

  .module-card {
    height: 100%;
    border: 1px solid #eee;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
    display: flex;
    flex-direction: column;
  }

  .card-header {
    font-size: 16px;
    font-weight: bold;
    padding: 10px 20px;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
  }

  .mt-20 {
    margin-top: 20px;
  }

  .framework-container {
    display: flex;
    padding: 20px;
    flex: 1;

    .product-group {
      flex: 1;
      margin-right: 20px;
      height: calc(100% - 30px);

      &:last-child {
        margin-right: 0;
      }

      .group-title {
        font-size: 14px;
        font-weight: bold;
        margin-bottom: 10px;
        padding-bottom: 5px;
        min-height: 20px; /* 最小高度 */
        border-bottom: 1px solid #f0f0f0;
      }

      .scroll-container {
        transition: transform 0.3s ease;
        will-change: transform;
      }

      .product-list {
        margin: 0;
        padding: 0;
        list-style: none;

        li {
          line-height: 28px;
          color: #666;
          padding: 0 5px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          // 添加动画过渡效果
          transition: all 0.3s ease;

          &:hover {
            color: #409EFF;
            transform: translateX(5px);
          }
        }
      }

      .product-list1 {
        list-style: none;
        height: 315px;
        padding: 0;
        margin: 0;

        li {
          line-height: 28px;
          color: #666;
          padding: 0 5px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
  }

  .sales-container, .purchase-container {
    padding: 15px;
    flex: 1;
    display: flex;
    flex-direction: column;
  }

  .card-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
    flex: 1;
    align-content: center;
  }

  .stat-card {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 15px;
    border: 1px solid #eee;
    position: relative;
    transition: all 0.2s ease;

    &:hover {
      transform: translateY(-3px);
      box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
    }

    .card-label {
      font-size: 13px;
      color: #666;
    }

    .card-value {
      display: block;
      font-size: 18px;
      font-weight: bold;
      margin: 5px 0;
      color: #333;
    }

    .card-icon {
      position: absolute;
      top: 15px;
      right: 15px;
      font-size: 20px;
      opacity: 0.7;
    }
  }

  .chart-container {
    padding: 20px;
    flex: 1;
    display: flex;
    flex-direction: column;

    .distribution-chart {
      flex: 1;
      width: 100%;
      min-height: 200px;
    }

    .chart-legend {
      margin-top: 15px;
      max-height: 80px;
      overflow-y: auto;

      .legend-item {
        display: flex;
        align-items: center;
        margin-bottom: 5px;
        font-size: 12px;

        .color-dot {
          width: 10px;
          height: 10px;
          border-radius: 50%;
          margin-right: 5px;
        }

        .legend-name {
          flex: 1;
        }

        .legend-value {
          color: #666;
        }
      }
    }
  }

  .total-count {
    font-size: 14px;
    font-weight: normal;
    color: #666;
  }
}
</style>
